package com.city.subscription.service.impl;

import com.city.subscription.entity.imageReturMessage;
import com.city.subscription.entity.returMessage;
import com.city.subscription.entity.textReturMessage;
import com.city.subscription.service.wxService;
import com.city.subscription.utils.Robot;
import com.thoughtworks.xstream.XStream;
import net.sf.json.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

import javax.servlet.ServletInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created with IntelliJ IDEA.
 * User: Cheng
 * Date: 2020/10/22
 * Time: 23:17
 * Description: No Description
 */
@Service
public class weServiceImpl implements wxService {
    private static final String TOKEN="city";
    private static final String APPKEY="1fec136dbd19f44743803f89bd55ca62";
    private static final String URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxd54cd826868bebe5&secret=82741763a08bebb3092d8e43e33032d7";

    @Override
    public Boolean getToken(String signature, String timestamp, String nonce) {
        String [] Verification=new String [] {TOKEN,timestamp,nonce};
        Arrays.sort(Verification);
        String str=Verification[0]+Verification[1]+Verification[2];
        String sha1Str=sha1(str);
        return sha1Str.equalsIgnoreCase(signature);
    }

    @Override
    public Map<String, String> parseRequest(ServletInputStream inputStream) {
        Map<String ,String > map=new HashMap<>();
        SAXReader saxReader = new SAXReader();
        try {
            Document read = saxReader.read(inputStream);
            Element rootElement = read.getRootElement();
            List<Element> elements = rootElement.elements();
            for (Element element : elements) {
                map.put(element.getName(),element.getStringValue());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public String getRespost(Map<String, String> parseRequest) {
        //解析map查数据库，应该返回什么信息，然后返回固定格式得xml给微信端进行回复用户
        returMessage msg=null;
        String msgType = parseRequest.get("MsgType");
        switch (msgType){
            case "text":
                //text消息就返回textReturMessage对象
                msg=getMessage(parseRequest);
                break;
            case "image":
                //text消息就返回textReturMessage对象
                break;
            case "voice":
                break;
            case "amr":
                break;
            case "video":
                break;
            case "shortvideo":
                break;
            case "location":
                break;
            case "link":
                break;
        }
        //消息对象转xml格式返回
        XStream xStream = new XStream();
        xStream.processAnnotations(textReturMessage.class);
        xStream.processAnnotations(imageReturMessage.class);
        /*
        * .
        * .
        * .
        * */
        String s = xStream.toXML(xStream);
        return s;
    }

    private static returMessage getMessage(Map<String,String> parseRequest){
        //聊天机器人，回复文本消息
        String content = parseRequest.get("Content");

        if (content.equals("图文")){
            
        }

        String content1 = getContent(content);
        textReturMessage textReturMessage = new textReturMessage(parseRequest, content1);
        return textReturMessage;
    }

    private static String getContent(String content){
        String result =null;
        String url ="http://op.juhe.cn/robot/index";//请求接口地址
        Map params = new HashMap();//请求参数
        params.put("key",APPKEY);//您申请到的本接口专用的APPKEY
        params.put("info",content);//要发送给机器人的内容，不要超过30个字符
        params.put("dtype","");//返回的数据的格式，json或xml，默认为json
        params.put("loc","");//地点，如北京中关村
        params.put("lon","");//经度，东经116.234632（小数点后保留6位），需要写为116234632
        params.put("lat","");//纬度，北纬40.234632（小数点后保留6位），需要写为40234632
        params.put("userid","");//1~32位，此userid针对您自己的每一个用户，用于上下文的关联

        try {
            result = Robot.net(url, params, "GET");
            JSONObject jsonObject = JSONObject.fromObject(result);
            Integer error_code = jsonObject.getInt("error_code");
            if (error_code!=0){
                return null;
            }
            JSONObject result1 = jsonObject.getJSONObject("result");
            String text = result1.getString("text");
            return text;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String sha1(String str) {
        StringBuilder sb=new StringBuilder();
        try {
            MessageDigest sha1 = MessageDigest.getInstance("sha1");
            byte[] digest = sha1.digest(str.getBytes());
            char[]chars={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
            for (byte b : digest) {
                sb.append(chars[(b>>4)&15]);
                sb.append(chars[b&15]);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    //获取token
    public String getToken1() throws MalformedURLException {
        java.net.URL url = new URL(URL);
        try {
            URLConnection urlConnection = url.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            byte[] b=new byte[1024];
            int len;
            StringBuilder stringBuilder = new StringBuilder();
            while ((len=inputStream.read(b))!=-1){
                stringBuilder.append(new String(b,0,len));
            }
            String s = stringBuilder.toString();
            JSONObject jsonObject = JSONObject.fromObject(s);
            String access_token = jsonObject.getString("access_token");
            String expires_in = jsonObject.getString("expires_in");
            Long comTime=System.currentTimeMillis()+Long.parseLong(expires_in)*1000;
            if (System.currentTimeMillis()>comTime){
                return getToken1();
            }else {
                return access_token;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return getToken1();
    }
}
